<template>
  <div class="faceUpload">
    <el-upload
      class="avatar-uploader"
      :auto-upload="false"
      :action="uploadFileUrl"
      :on-change="handleChange"
      :show-file-list="false"
      :headers="headers"
      ref="fileUpload"
    >
      <el-image
        v-if="previewUrl"
        class="avatar"
        fit="cover"
        :src="previewUrl"
      />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
    <div type="text" class="take-btn" @click="takePhoto">拍摄</div>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  tips: {
    type: String,
    default: "",
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf"],
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:modelValue"]);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const previewUrl = ref();


watch(() => props.modelValue, val => {
  if (val) {
    // 判断是不是file类型
    if (val instanceof File) {
      previewUrl.value = URL.createObjectURL(val);
    } else {
      previewUrl.value = "data:image/png;base64," + val
    }
  } else {
    previewUrl.value = "";
    return undefined
  }
},{ deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(
        `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
      );
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  return true;
}

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
function handleChange(file) {
  handleBeforeUpload(file);
  emit("update:modelValue", file.raw);
}


// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}

/**
 * 拍照
 */
function takePhoto(){
  console.log('拍摄');
  alert('开发中');
}
</script>

<style scoped lang="scss">
.faceUpload{
  .avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  &:hover {
    border-color: var(--el-color-primary);
  }

  .avatar {
    width: 120px;
    height: 120px;
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
  }
}
.take-btn {
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  color: var(--el-color-primary);
}
}
</style>
